package com.buli.blmall.admin.exception.handler;

import com.buli.blmall.admin.common.response.Result;
import com.buli.blmall.admin.exception.LoginException;
import com.buli.blmall.admin.exception.SmsException;
import com.buli.blmall.admin.exception.error.LoginErrorCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * @author xiang.gao
 * @date 2024/12/18 11:35
 */
@Slf4j
@RestControllerAdvice
public class GolbalExceptionHandler {

    /**
     * 方法参数异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        log.warn("请求地址:{},参数校验失败:{}", request.getRequestURI(), defaultMessage);
        return Result.paramsError(defaultMessage);
    }

    /**
     * 短信异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(SmsException.class)
    public Result<Boolean> handleSmsException(SmsException e, HttpServletRequest request) {
        log.warn("请求地址:{},发送短信异常:{}", request.getRequestURI(), e.getMessage());
        return Result.failure(e.getCode(), e.getMessage());
    }

    /**
     * 登录异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(LoginException.class)
    public Result<Boolean> handleLoginException(LoginException e, HttpServletRequest request) {
        log.warn("请求地址:{},登录异常:{}", request.getRequestURI(), e.getMessage());
        return Result.failure(e.getCode(), e.getMessage());
    }

    /**
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result handleBadCredentialsException(BadCredentialsException e, HttpServletRequest request) {
        log.warn("请求地址:{},登录异常:{}", request.getRequestURI(), e.getMessage());
        return Result.loginError(LoginErrorCode.LOGIN_FAILED);
    }

    /**
     * 运行时异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<Boolean> handelRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("请求地址{},发生运行异常", request.getRequestURI(), e);
        return Result.error();
    }


}
